<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f9;
            padding: 20px;
        }

        h1 {
            text-align: center;
            color: #333;
        }

        form {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            color: #666;
        }

        input[type="text"],
        input[type="email"],
        input[type="password"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            padding: 10px 20px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        th,
        td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        tr:hover {
            background-color: #f1f1f1;
        }

        .pagination {
            margin-top: 20px;
            text-align: center;
        }

        .pagination button {
            margin: 0 5px;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 30%;
            border-radius: 8px;
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <h1>用户管理系统</h1>
    <!-- 添加用户表单 -->
    <form id="addUserForm">
        <label for="username">用户名:</label>
        <input type="text" id="username" required>
        <label for="email">邮箱:</label>
        <input type="email" id="email" required>
        <label for="password">密码:</label>
        <input type="password" id="password" required>
        <button type="submit">添加用户</button>
    </form>
    <!-- 用户列表 -->
    <table id="userTable">
        <thead>
            <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>邮箱</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <!-- 用户数据将动态填充 -->
        </tbody>
    </table>
    <!-- 分页按钮 -->
    <div class="pagination">
        <button id="prevPageButton" disabled>上一页</button>
        <button id="nextPageButton">下一页</button>
    </div>

    <!-- 编辑用户模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2>编辑用户信息</h2>
            <form id="editUserForm">
                <label for="editUsername">用户名:</label>
                <input type="text" id="editUsername" required>
                <label for="editEmail">邮箱:</label>
                <input type="email" id="editEmail" required>
                <label for="editPassword">密码:</label>
                <input type="password" id="editPassword" required>
                <input type="hidden" id="editUserId">
                <button type="submit">保存</button>
            </form>
        </div>
    </div>

    <script>
        const baseUrl = 'http://localhost:9999/users';
        let currentPage = 0;
        const pageSize = 4;
        const sortField = 'username';
        const sortDirection = 'DESC';

        // 获取模态框元素
        const editModal = document.getElementById('editModal');
        const closeBtn = document.querySelector('.close');
        const editUserForm = document.getElementById('editUserForm');

        // 页面加载时获取用户列表
        window.onload = function () {
            fetchUsers();
        };

        // 添加用户表单提交事件
        document.getElementById('addUserForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const username = document.getElementById('username').value;
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;
            const user = {
                username: username,
                email: email,
                password: password
            };
            addUser(user);
        });

        // 获取用户列表
        function fetchUsers() {
            const url = `${baseUrl}?page=${currentPage}&size=${pageSize}&sortField=${sortField}&sortDirection=${sortDirection}`;
            fetch(url)
              .then(response => response.json())
              .then(data => {
                    const tableBody = document.querySelector('#userTable tbody');
                    tableBody.innerHTML = '';
                    data.content.forEach(user => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${user.id}</td>
                            <td>${user.username}</td>
                            <td>${user.email}</td>
                            <td>
                                <button onclick="deleteUser(${user.id})">删除</button>
                                <button onclick="editUser(${user.id})">编辑</button>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                    // 更新分页按钮状态
                    const prevPageButton = document.getElementById('prevPageButton');
                    const nextPageButton = document.getElementById('nextPageButton');
                    prevPageButton.disabled = currentPage === 0;
                    nextPageButton.disabled = data.last;
                })
              .catch(error => console.error('Error fetching users:', error));
        }

        // 添加用户
        function addUser(user) {
            fetch(baseUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(user)
            })
              .then(response => response.json())
              .then(() => {
                    fetchUsers();
                    document.getElementById('addUserForm').reset();
                })
              .catch(error => console.error('Error adding user:', error));
        }

        // 删除用户
        function deleteUser(id) {
            if (confirm('确定要删除该用户吗？')) {
                const url = `${baseUrl}/${id}`;
                fetch(url, {
                    method: 'DELETE'
                })
                  .then(() => fetchUsers())
                  .catch(error => console.error('Error deleting user:', error));
            }
        }

        // 编辑用户
        function editUser(id) {
            // 先获取用户详情
            fetch(`${baseUrl}/${id}`)
              .then(response => response.json())
              .then(user => {
                    // 填充模态框表单
                    document.getElementById('editUsername').value = user.username;
                    document.getElementById('editEmail').value = user.email;
                    document.getElementById('editPassword').value = user.password;
                    document.getElementById('editUserId').value = user.id;
                    // 显示模态框
                    editModal.style.display = 'block';
                })
              .catch(error => console.error('Error fetching user details:', error));
        }

        // 关闭模态框
        closeBtn.onclick = function () {
            editModal.style.display = 'none';
        };

        // 点击模态框外部关闭
        window.onclick = function (event) {
            if (event.target === editModal) {
                editModal.style.display = 'none';
            }
        };

        // 编辑用户表单提交事件
        editUserForm.addEventListener('submit', function (e) {
            e.preventDefault();
            const id = document.getElementById('editUserId').value;
            const username = document.getElementById('editUsername').value;
            const email = document.getElementById('editEmail').value;
            const password = document.getElementById('editPassword').value;
            const updatedUser = {
                username: username,
                email: email,
                password: password
            };
            updateUser(id, updatedUser);
            // 关闭模态框
            editModal.style.display = 'none';
        });

        // 更新用户
        function updateUser(id, user) {
            const url = `${baseUrl}/${id}`;
            fetch(url, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(user)
            })
              .then(response => response.json())
              .then(() => fetchUsers())
              .catch(error => console.error('Error updating user:', error));
        }

        // 上一页
        function prevPage() {
            if (currentPage > 0) {
                currentPage--;
                fetchUsers();
            }
        }

        // 下一页
        function nextPage() {
            currentPage++;
            fetchUsers();
        }

        document.getElementById('prevPageButton').addEventListener('click', prevPage);
        document.getElementById('nextPageButton').addEventListener('click', nextPage);
    </script>
</body>

</html>